package com.community.controller;

import com.community.common.Captcha;
import com.community.common.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码
 * Created by Administrator on 2018/5/3 0003.
 */
@RestController
@RequestMapping("/code/")
@CrossOrigin(origins = Const.REQUESTURL,maxAge = 3600,allowCredentials = "true")
public class SecCodeController {


    private Logger logger = LoggerFactory.getLogger(SecCodeController.class);

    /**
     * pc网页登录请求
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "pccode.do")
    public void pcGenerateCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        generateCode(request,response,Const.CodeType.PCLOGINSTRCODE);
    }

    /**
     * 移动登录网页请求
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "appcode.do")
    public void appGenerateCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        generateCode(request,response,Const.CodeType.APPLOGINSTRCODE);
    }

    /**
     * 邮寄申请网页请求
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "mailServerCode.do")
    public void mailGenerateCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        generateCode(request,response,Const.CodeType.MAILSERVERCODE);
    }

    /**
     * 验证码
     * @param request
     * @param response
     * @param type
     * @throws IOException
     */
    public void generateCode(HttpServletRequest request, HttpServletResponse response, String type) throws IOException{
        Captcha captcha = new Captcha(100,30,20);
        String codeStr = captcha.getString();//验证码字符
        request.getSession().setAttribute(type,codeStr);
        logger.info("验证码为："+codeStr);
        ImageIO.write(captcha.getBuffImage(),"JPEG",response.getOutputStream());
        captcha = null;
    }


}
